package com.zhangkunhao.notes.web.servlet;

import com.alibaba.fastjson.JSON;
import com.zhangkunhao.notes.entity.Do.CollectQuestion;
import com.zhangkunhao.notes.entity.Do.Question;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.service.CollectQuestionServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

/**
 * 问题收藏夹的controller
 *
 * @author 20642
 */
@WebServlet("/collectQuestion/*")
public class CollectQuestionServlet extends BaseDaoServlet {

    private CollectQuestionServiceImpl collectQuestionService = new CollectQuestionServiceImpl();

    public void collectQuestion(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据
        String params = request.getReader().readLine();

        //2.转为对象
        Question question = JSON.parseObject(params, Question.class);

        // 通过Session接收用户Id
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");

        //3.调用service层,封装返回前端的对象
        Message<Question> questionMessage = collectQuestionService.collectQuestion(userId, question);

        //4.写数据,转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(questionMessage));
    }

    public void showQuestionDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据
        int showQuestionId = Integer.parseInt(new String(request.getParameter("showQuestionId").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));

        //2.调用service层,封装返回前端的对象
        Message<Question> questionMessage = collectQuestionService.showQuestionDetails(showQuestionId);

        //3.写数据,转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(questionMessage));
    }


    public void showMyCollectQuestions(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据
        Integer userId = (Integer) request.getSession().getAttribute("userId");

        //2.调用service
        PageBean<CollectQuestion> collectQuestionPageBean = collectQuestionService.showMyCollectQuestions(userId);

        //3.转换为json数据,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(collectQuestionPageBean));
    }

}
